package com.ss.android.article.base.feature.feed.vh;

import android.util.SparseArray;
import android.view.View;

import com.bytedance.common.utility.Logger;
import com.ss.android.article.common.SingleTypeViewPool;

public final class CardViewPools {
    private SparseArray<SingleTypeViewPool> sparseArray;
    private int capacity;

    public CardViewPools() {
        this.sparseArray = new SparseArray();
        this.capacity = 6;
        if (this.capacity <= 0) {
            throw new IllegalArgumentException("The ViewPool capacity must more than 0.");
        }
    }

    public final View acquire(int type) {
        View result = null;
        SingleTypeViewPool singlePool = this.sparseArray.get(type);
        if (singlePool != null) {
            if (singlePool.currentSize > 0) {
                int lastIndex = singlePool.currentSize - 1;
                result = (View) singlePool.array[lastIndex];
                singlePool.array[lastIndex] = null;
                --singlePool.currentSize;
            }
        }
        if (Logger.debug()) {
            Logger.d("CardViewPools", "CardViewPools.acquire: type = " + type + ", result = " + result);
        }
        return result;
    }

    public final boolean release(int type, View view) {
        SingleTypeViewPool v0_1;
        boolean v2 = false;
        v0_1 = (SingleTypeViewPool) this.sparseArray.get(type);
        if (v0_1 == null) {
            v0_1 = new SingleTypeViewPool(this.capacity);
            this.sparseArray.put(type, v0_1);
        }

        int v1 = 0;
        while (true) {
            if (v1 >= v0_1.currentSize) {
                v1 = 0;
                break;
            } else if (v0_1.array[v1] == view) {
                v1 = 1;
            } else {
                ++v1;
                continue;
            }

            break;
        }
        if (v1 != 0) {
            throw new IllegalStateException("Already in the pool!");
        }

        if (v0_1.currentSize < v0_1.array.length) {
            v0_1.array[v0_1.currentSize] = view;
            ++v0_1.currentSize;
            v2 = true;
        }

        if (Logger.debug()) {
            Logger.d("CardViewPools", "CardViewPools.release: type = " + type + ", result = " + v2);
        }
        return v2;
    }
}

